#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <signal.h>
#include "Common.hpp"

int sockfd;
struct sockaddr_in server;

void handler(int signo)
{
    std::string message = "QUIT";
    int n = ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));
    (void)n;
    exit(0);
}

void* Recver(void* args)
{
    (void)args;
    while (true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buff[1024];
        int n = ::recvfrom(sockfd, buff, sizeof(buff)-1, 0, CONV(&temp), &len);
        if (n > 0)
        {
            buff[n] = 0;
            std::cout << buff << std::endl;
        }
    }
    return nullptr;
}

// ./client_udp serverip serverport
int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " serverip serverport" << std::endl;
        Die(USAGE_ERR);
    }
    signal(2, handler);
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 1.创建套接字
    sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        Die(SOCKET_ERR);
    }
    // 2.填充服务器信息
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = ::htons(serverport);
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    pthread_t tid;
    pthread_create(&tid, nullptr, Recver, nullptr);

    std::string msg = "我来了哈！";
    ::sendto(sockfd, msg.c_str(), msg.size(), 0, CONV(&server), sizeof(server));

    while (true)
    {
        std::cout << "Please Enter@ ";
        std::string message;
        std::getline(std::cin, message);
        int n = sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));
        (void)n;
    }

    pthread_join(tid, nullptr);
    return 0;
}